extends CanvasLayer

@onready var stats: PanelContainer = %Stats

@onready var fps: Label = %FPS

@onready var memory: Label = %Memory

@onready var object: Label = %Object

@onready var draw_call: Label = %DrawCall


func _ready() -> void:
	process_mode = Node.PROCESS_MODE_ALWAYS


func _process(_delta: float) -> void:
	fps.text = (
		"FPS: %.1f (Process: %.2f ms)"
		% [
			Performance.get_monitor(Performance.TIME_FPS),
			Performance.get_monitor(Performance.TIME_PROCESS) * 1000
		]
	)

	memory.text = (
		"Memory: %s" % _format_memory(Performance.get_monitor(Performance.MEMORY_STATIC))
	)

	object.text = (
		"Objects: %d | Nodes: %d | Resources: %d"
		% [
			Performance.get_monitor(Performance.OBJECT_COUNT),
			Performance.get_monitor(Performance.OBJECT_NODE_COUNT),
			Performance.get_monitor(Performance.OBJECT_RESOURCE_COUNT)
		]
	)

	draw_call.text = (
		"Draw calls: %d" % Performance.get_monitor(Performance.RENDER_TOTAL_DRAW_CALLS_IN_FRAME)
	)


func _format_memory(bytes: float) -> String:
	if bytes < 1024:
		return "%d B" % bytes
	elif bytes < 1024 * 1024:
		return "%.1f KB" % (bytes / 1024)
	elif bytes < 1024 * 1024 * 1024:
		return "%.1f MB" % (bytes / (1024 * 1024))
	else:
		return "%.1f GB" % (bytes / (1024 * 1024 * 1024))


func _input(event: InputEvent) -> void:
	if event.is_action_pressed("open_profilers"):
		stats.visible = not stats.visible
